package com.hsq.jdbc.transaction_;

import com.hsq.jdbc.utils.JDBCUtils;
import org.junit.jupiter.api.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Transaction_ {

    @Test
    public void noTransaction() {
        Connection connection = JDBCUtils.getConnection();
        String sql1 = "update account set balance = balance - 100 where id = ?";
        String sql2 = "update account set balance = balance + 100 where id = ?";
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql1);
            preparedStatement.setInt(1, 1);
            preparedStatement.executeUpdate();
            int i = 10 / 0;
            preparedStatement = connection.prepareStatement(sql2);
            preparedStatement.setInt(1, 2);
            preparedStatement.executeUpdate();

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.close(null, preparedStatement, connection);
        }
    }

    @Test
    public void Transaction() {
        Connection connection = null;
        String sql1 = "update account set balance = balance - 100 where id = ?";
        String sql2 = "update account set balance = balance + 100 where id = ?";
        PreparedStatement preparedStatement = null;
        try {
            connection = JDBCUtils.getConnection();//在默认情况下，connection是自动提交的
            //将connection设置为不自动提交事务
            connection.setAutoCommit(false);//相当于开启事务
            preparedStatement = connection.prepareStatement(sql1);
            preparedStatement.setInt(1, 1);
            preparedStatement.executeUpdate();
//            int i = 10 / 0;
            preparedStatement = connection.prepareStatement(sql2);
            preparedStatement.setInt(1, 2);
            preparedStatement.executeUpdate();
            //无异常则提交事务
            connection.commit();
        } catch (SQLException e) {
            //这里我们可以进行回滚，即撤销执行SQL
            //默认回滚到事务开启的状态
            System.out.println("执行发生异常，撤销执行SQL");
            try {
                connection.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            e.printStackTrace();
        } finally {
            JDBCUtils.close(null, preparedStatement, connection);
        }
    }
}
